package Calendar;

import java.util.Calendar;

public class MyCalendar {
	
	private int year;
	private int month;
	
	public MyCalendar(){}
	
	public MyCalendar(int year,int month){
		
		//月份不合法
		if(month<0||month>12){
			throw new CalendarException("月份不合法!");
		}
		
		this.month=month;
		this.year=year;
	}

	public void setYear(int year) {
		this.year = year;
	}

	public void setMonth(int month) {
		this.month = month;
	}

	@Override
	public String toString() {
		return getCalendar();
	}
	
	public String getCalendar(){
		
		StringBuilder sb=new StringBuilder();
		
		//以默认的时区获取一个日历对象
		Calendar cal=Calendar.getInstance();
		
		cal.set(year, month, 1);
		//日期设置到一个月的第一天
		cal.set(Calendar.DAY_OF_MONTH, 1);
		//获取这一天是星期几
		int weekday = cal.get(Calendar.DAY_OF_WEEK);
		
		
		//一个星期的第一天是星期几,使用默认的，星期日为第一天
		int fistDayOfWeek =cal.getFirstDayOfWeek();
		
		
		String[] weeks=new String[]{"周日","周一","周二","周三","周四","周五","周六"};	       
		for(String str:weeks){
			sb.append(str+"\t");
		}
		sb.append("\n");
		//为了正确显示本月第一天的位置
		
		Calendar ctemp=(Calendar) cal.clone();
		while(weekday!=fistDayOfWeek){
			sb.append("\t");
			ctemp.add(Calendar.DAY_OF_MONTH, -1);
        	weekday=ctemp.get(Calendar.DAY_OF_WEEK);
		}
		
		//本月分
		int thisMonth=cal.get(Calendar.MONTH);
		//日期设置到一个月的第一天
		cal.set(Calendar.DAY_OF_MONTH, 1);
		
		while(cal.get(Calendar.MONTH)==thisMonth){
			
			int day = cal.get(Calendar.DAY_OF_MONTH);
			sb.append(day+"\t");
			//加一天
			cal.add(Calendar.DAY_OF_MONTH,1);
			
			weekday = cal.get(Calendar.DAY_OF_WEEK);
			
			
			if(weekday == Calendar.SUNDAY){
				sb.append("\n");
			}
		}
		
		return sb.toString();
	}
	

}






